import java.util.HashMap;
import java.util.Map;

//水果成篮
public class totalFruit {
    //方式一：使用HashMap容器
    public int totalFruit(int[] fruits) {
        Map<Integer, Integer> hash = new HashMap<>();

        int n = fruits.length;
        int ret = -1;
        for (int left = 0, right = 0; right < n; right++){
            int in = fruits[right];
            hash.put(in, hash.getOrDefault(in, 0) + 1);

            while (hash.size() > 2){
                int out = fruits[left];
                hash.put(out, hash.get(out) - 1);

                if (hash.get(out) == 0){
                    hash.remove(out);
                }

                left++;
            }

            ret = Math.max(ret, right - left + 1);
        }

        return ret;
    }

    //方式二：使用数组来模拟HashMap
    public int code(int[] fruits) {
        int[] hash = new int[fruits.length];
        int ret = -1;

        for (int left = 0, right = 0, kinds = 0; right < fruits.length; right++){
            int in = fruits[right];
            if (hash[in] == 0){
                kinds++;
            }
            hash[in]++;

            while(kinds > 2){
                int out = fruits[left];
                hash[out]--;
                if (hash[out] == 0){
                    kinds--;
                }

                left++;
            }

            ret = Math.max(ret, right - left + 1);
        }

        return ret;
    }

    public static void main(String[] args) {
    }
}
